package cn.iocoder.yudao.module.scrm.controller.admin.business;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.module.scrm.annotations.EncryptPhoneNumbers;
import cn.iocoder.yudao.module.scrm.controller.admin.business.vo.business.BusinessDetailVO;
import cn.iocoder.yudao.module.scrm.controller.admin.business.vo.business.BusinessPageReqVO;
import cn.iocoder.yudao.module.scrm.controller.admin.business.vo.business.BusinessRespVO;
import cn.iocoder.yudao.module.scrm.controller.admin.business.vo.business.BusinessSaveReqVO;
import cn.iocoder.yudao.module.scrm.service.business.BusinessService;
import cn.iocoder.yudao.module.system.api.permission.PermissionApi;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Collections;
import java.util.List;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Tag(name = "管理后台 - SCRM 商机")
@RestController
@RequestMapping("/scrm/business")
@Validated
public class BusinessController {

    @Resource
    private AdminUserApi adminUserApi;

    @Resource
    private BusinessService businessService;

    @Resource
    private PermissionApi permissionApi;

    @PostMapping("/create")
    @Operation(summary = "创建商机")
    @PreAuthorize("@ss.hasPermission('scrm:business:create')")
    public CommonResult<Integer> createBusiness(@Valid @RequestBody BusinessSaveReqVO createReqVO) {
        return success(businessService.createBusiness(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新商机")
    @PreAuthorize("@ss.hasPermission('scrm:business:update')")
    public CommonResult<Boolean> updateBusiness(@Valid @RequestBody BusinessSaveReqVO updateReqVO) {
        businessService.updateBusiness(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除商机")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('scrm:business:delete')")
    public CommonResult<Boolean> deleteBusiness(@RequestParam("id") Integer id) {
        businessService.deleteBusiness(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得商机")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('scrm:business:query')")
    @EncryptPhoneNumbers
    public CommonResult<BusinessDetailVO> getBusiness(@RequestParam("id") Integer id,@RequestHeader(value = "Tenant-Id") String tenantId) {
        BusinessDetailVO business = businessService.getBusinessDetail(id,tenantId);
        return success(BeanUtils.toBean(business, BusinessDetailVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得商机分页")
    @PreAuthorize("@ss.hasPermission('scrm:business:query')")
    public CommonResult<PageResult<BusinessRespVO>> getBusinessPage(@Valid BusinessPageReqVO pageReqVO,@RequestHeader("Tenant-Id") Integer tenantId) {
        //不是超级管理员默认查询自己的数据-是超级管理员直接查询所有的
        Long loginUserId = getLoginUserId();
        if(CollectionUtils.isAnyEmpty(pageReqVO.getUserIds()) && !permissionApi.roleIsSuperAdmin(loginUserId).getCheckedData()) {
            //用户id转成企业微信wxId进行查询
            pageReqVO.setUserIds(Collections.singletonList(adminUserApi.getUserNotCheckDataPermission(getLoginUserId()).getCheckedData().getWxUserId()));
        }
        PageResult<BusinessRespVO> pageResult = businessService.getBusinessPage(pageReqVO,tenantId);
        return success(pageResult);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出商机 Excel")
    @PreAuthorize("@ss.hasPermission('scrm:business:export')")
    @OperateLog(type = EXPORT)
    public void exportBusinessExcel(@Valid BusinessPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<BusinessRespVO> list = businessService.getBusinessPageExport(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "商机.xls", "数据", BusinessRespVO.class,
                        BeanUtils.toBean(list, BusinessRespVO.class));
    }

}